package com.ruoyi.common.utils.aspose;

import com.ruoyi.common.utils.file.FileUtils;
import com.vladsch.flexmark.ast.Node;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.parser.ParserEmulationProfile;
import com.vladsch.flexmark.util.options.MutableDataSet;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;

/**
 * TODO 类描述
 *
 * @author ysz
 * @date 2024/2/1 19:08
 */
public class MarkDownWrapper implements FileWrapper {
    /**
     * markdown to html
     *
     * @param  multipartFile markdown contents
     * @return parse html contents
     */
    @Override
    public FileContentEntity convertToHtmlContent(MultipartFile multipartFile) throws IOException {
        InputStream stream = multipartFile.getInputStream();
        String htmlContent = IOUtils.toString(stream, "UTF-8");
        MutableDataSet options = new MutableDataSet();
        options.setFrom(ParserEmulationProfile.MARKDOWN);

        // enable table parse!
        options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create()));

        Parser parser = Parser.builder(options).build();
        HtmlRenderer renderer = HtmlRenderer.builder(options).build();

        Node document = parser.parse(htmlContent);
        String fileName = FileUtils.getNameNotSuffix(multipartFile.getOriginalFilename());
        return new FileContentEntity(fileName, renderer.render(document));
    }
}
